// packageA/pages/repairEdit/repairEdit.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:null,
    //传参来的id
    id:null,
    //修改信息回显
    editInfo:{},
    editInfoOld:{},
    //提交按钮禁用
    disabled:false,
    //选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false,
    //接待时间选择框
    showProcessingTime:false, 
    //完成时间选择框
    showCompleteDate:false, 
    //当前时间
    currentProcessingTime: new Date().getTime(), 
    currentCompleteDate: new Date().getTime(), 
    //最大时间
    maxDate1: new Date().getTime(),
    //时间格式
    formatter (type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      } else if (type === 'hour') {
        return `${value}时`
      } else if (type === 'minute') {
        return `${value}分`
      } else if (type === 'second') {
        return `${value}秒`
      }
      return value
    },
    //时间格式
    formatter2 (type, value) {
      if (type === 'hour') {
        return `${value} 点`
      } else if (type === 'minute') {
        return `${value} 分`
      }
      return value
    },
    //服务记录
    serviceList:[],
    //查询的设备表中业务员
	salesman: null,
	//设备信息
	equipmentInfo: null,
    //上传路径
    ossUploadUrl: app.globalData.ossUrl
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {    
    if(options.paramObj){
      this.setData({
        paramObj: JSON.parse(options.paramObj)
      })

      console.log('维修接待传参');
      console.log(JSON.parse(options.paramObj));

      //查询设备表中业务员（查完再获取维修工单修改数据）
      this.getEquipmentInfo();      
    }
  },    

  //提交表单###
  confirmForm(e){
    this.setData({
      disabled:true
    })

    let obj=e.detail.value;
    let td=this.data;
    let info=td.editInfo;
    let old=td.editInfoOld;
    let user=app.globalData.userInfo;  
    let serviceDetails=info.serviceDetails;
    //故障时间
    let faultTypeDate=info.faultTypeDate;

    //非空验证
      //故障类型
      if(!info.faultType){
        Toast.fail('请选择故障类型');
        return;
      }

      //处理方式
      if(!info.processMode){
        Toast.fail('请选择处理方式');
        return;
      }

      //真实故障描述
      let trueFault=obj.trueFault.trim();
      if(!trueFault){
        Toast.fail('请输入真实故障原因');
        return;
      }

      //处理结果
      let processResult=obj.processResult.trim();
      if(!processResult){
        Toast.fail('请输入处理结果');
        return;
      }

      //业务员必填
      if(info.salesman && info.salesman.id){
      }else{
        Toast.fail('请选择业务员');
        return;
      }

    //输入的工单服务记录
    let serviceList=td.serviceList;
    let newService=[];
    serviceList.forEach(item => {
		  if(item.content){
        newService.push(item);
		  }	
		});
    if(newService.length){
      serviceDetails=serviceDetails.concat(newService);
    }

    //处理工单记录
      //故障类型
      if(old.faultType){
        if(old.faultType.id!==info.faultType.id){
          serviceDetails.push({
            content: user.userName + '修改故障类型',
            datetime: util.timeFormat(new Date())
          });

          //修改了故障类型时，更新faultTypeDate字段
          faultTypeDate=util.timeFormat(new Date);
        }
      }else{
        serviceDetails.push({
          content: user.userName + '设置故障类型',
          datetime: util.timeFormat(new Date())
        });

        //第一次设置故障类型时，更新faultTypeDate字段
        faultTypeDate=util.timeFormat(new Date);
      }

      //处理方式
      if(old.processMode){
        if(old.processMode.id!==info.processMode.id){
          serviceDetails.push({
            content: user.userName + '修改处理方式',
            datetime: util.timeFormat(new Date())
          });
        }
      }else{
        serviceDetails.push({
          content: user.userName + '设置处理方式',
          datetime: util.timeFormat(new Date())
        });
      }

      //完成时间
      if(old.completeDate){
        if(old.completeDate!==info.completeDate){
          serviceDetails.push({
            content: user.userName + '修改完成时间',
            datetime: util.timeFormat(new Date())
          });
        }
      }else{
        serviceDetails.push({
          content: user.userName + '设置完成时间',
          datetime: util.timeFormat(new Date())
        });
      }    

    let param={
      className:'afterSaleMaintainOrder',
      data:{
        id: td.paramObj.id,
        //接待时间
        processingTime: info.processingTime,
        //完成时间
        completeDate: info.completeDate,
        //故障类型
        faultType: info.faultType,
        //真实故障
        trueFault: trueFault,
        //处理方式
        processMode: info.processMode,
        //处理结果
        processResult: processResult,
        //备注
        remark: obj.remark.trim(),
        //图片
        pic: info.pic,
        //工单记录
        serviceDetails: serviceDetails,
        //故障时间
        faultTypeDate: faultTypeDate,
        //业务员
				salesman: info.salesman,
				//外援上门次数
				numberOfForeignVisits: info.numberOfForeignVisits ? info.numberOfForeignVisits : 0
      }
		}
		
		//与建发数据对接
		let infoE = this.data.equipmentInfo;
		let param2={
			//设备id
			deviceld: infoE.id,
			//设备编码
			device_number: infoE.equipmentNo,
			//故障状态，编辑页面这里传1，完单时传0
			error_state: 1,
			//故障消息
			error_info: {
				//故障类型
				faultType: info.faultType,
				//真实故障
				trueFault: trueFault,
				//日期yyyy-mm-dd
				createDate: util.timeFormat(new Date())
			}
		}		

		// console.log(param.data);
		// return;

    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });  

    CommonService.goSave(param).then(res=>{
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');

        //如果业务员修改了需要同步到设备表
        if(td.salesman && (td.salesman.id!=info.salesman.id)){
          this.changeEquipmentSalesman();
				}

				//是否修改设备状态为故障
				//this.shutdownDevice(td.paramObj.id);

				//获取上一级页面
				let pages = getCurrentPages();
				let prevPage = pages[pages.length - 2];				
				//建发消息推送 传参：设备id、设备和故障信息
				prevPage.whichCompanyEquipment(infoE.id, param2);

        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
    })
  },

  //获取修改数据
  getInfo(){
    let param = {
      isAuth: false,
      className: 'afterSaleMaintainOrder',
      data: {
        id:this.data.paramObj.id,
        selectFields: ["id","receiver","processingTime","serviceDetails","completeDate","faultType","processMode","trueFault","pic","processResult","remark","faultTypeDate","salesman","numberOfForeignVisits"]
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let info=res.data.data.result[0];        

        //保存修改前信息，用于记入工单记录
        let obj={
          completeDate: info.completeDate,
          faultType: info.faultType,
          processMode: info.processMode       
        }
        this.setData({
          editInfoOld: obj
        })

        //完成时间        
        info.completeDate=util.timeFormat(new Date);  

        //处理图片
        if(info.pic && info.pic.length){
          let pics=[];
          info.pic.forEach(item => {
            pics.push(item.url);
          });
          info.self_pic=pics;
        }

        //业务员-取设备表中值，如果没有则为接单人
        if(info.salesman && info.salesman.name){
        }else{
          if(this.data.salesman){      
            info.salesman=this.data.salesman;
          }else{
            info.salesman=info.receiver;
          }
				}			

        console.log('维修接待回显');
        console.log(info);

        this.setData({
          editInfo: info
        }) 
      }
    }).catch((error) => {
    })
  },

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  },  

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.refreshListAndPage();
    wx.navigateBack();
  },

  //获取图片上传组件的传值
  getUploadUrl(data){
    let imgUrls=data.detail;
    if(imgUrls.length){
      let imgArr=[];
      imgUrls.forEach(item => {
        imgArr.push({
          url:item
        });
      });

      let pic='editInfo.pic';
      this.setData({
        [pic]: imgArr
      })
    } 
  }, 
  
  //显示接待时间
  onShowProcessingTime(){
    this.setData({
			showProcessingTime: true
    })
  },

  //隐藏接待时间
  onCloseProcessingTime(){
    this.setData({
			showProcessingTime: false
    })
  },

  //确认接待时间
  onConfirmProcessingTime(e) {
    let processingTime='editInfo.processingTime';
    this.setData({
      currentProcessingTime: e.detail,
      [processingTime]:util.timeFormat(e.detail),
    })
    this.onCloseProcessingTime();
  },

  //显示完成时间
  onShowCompleteDate(){
    this.setData({
			showCompleteDate: true
    })
  },

  //隐藏完成时间
  onCloseCompleteDate(){
    this.setData({
			showCompleteDate: false
    })
  },

  //确认完成时间-完成时间不能早于接待时间
  onConfirmCompleteDate(e) {
    //接待时间
    let processingTime=this.data.editInfo.processingTime;
    //分开日期和时间
    let pro_arr=processingTime.split(" ");    
    //今天
    let today=util.timeFormatDay(new Date);
    //显示的完成时间
    let times=null,s=null;

    //如果接待时间是今天
    if(pro_arr[0]==today){
      //分开小时和分钟
      let pro_time=pro_arr[1].split(":");
      let com_time=e.detail.split(":");
      //定义两个变量用于比较
      let h=null,m=null;
      
      if(com_time[0]<pro_time[0]){
        //选择的小时小于接待的小时，取接待的小时
        h = pro_time[0];
        s = '59';
      }else{
        //选择的小时大于等于接待的小时，正常取值
        h = com_time[0];
        s = '00';
      }
      
      if(com_time[0]<=pro_time[0] && com_time[1]<pro_time[1]){   
        //选择的小时小于等于接待的小时并且分钟小于接待的分钟，取接待的分钟 
        m = pro_time[1];
        s = '59';
      }else if(com_time[0]<=pro_time[0] && com_time[1]==pro_time[1]){
        //分钟相等时，秒取59
        m = com_time[1];
        s = '59';
      }else{ 
        //选择的小时大于接待的小时，或者小时相等但分钟大于接待的分钟，正常取值
        m = com_time[1];
        s = '00';
      }

      //连接时间
      times=h + ':' + m;
    }else{
      //非今天的正常取值
      times=e.detail;
      s = '00';
    }

    let completeDate='editInfo.completeDate';
    this.setData({
      currentCompleteDate: times,
      [completeDate]:util.timeFormatDay(new Date) + ' '+ times + ':' +s,
      disabled: false
    })
    this.onCloseCompleteDate();
  },

  //显示选择框
  onShowSelect(e){
    this.setData({
      selectList: []
    })

    let dataset=e.target.dataset;
    let field=dataset.field;

    this.setData({
      showSelect: true,
      selectField: field
    })

    //故障类型
    if(field=='faultType'){
      this.setData({
        selectTitle: '故障类型',
        showSelectSearch: true
      })
      this.getFaultTypeList();
    }

    //处理方式
    if(field=='processMode'){
      this.setData({
        selectTitle: '处理方式',
        showSelectSearch: true
      })
      this.getProcessModeList();
    }

    //业务员
    if(field=='salesman'){
      this.setData({
        selectTitle: '业务员',
        showSelectSearch: true
      })
      this.getSalesmanList();
    }
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: '',
      disabled: false
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //故障类型
    if(selectField=='faultType'){
      obj='editInfo.faultType';
    }

    //处理方式
    if(selectField=='processMode'){
      obj='editInfo.processMode';
    }

    //业务员
    if(selectField=='salesman'){
      obj='editInfo.salesman';
    }

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }

    this.onCloseSelect();
  },

  //清除选项
  onCancelSelect(){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //故障类型
    if(selectField=='faultType'){
      obj='editInfo.faultType';
    }

    //处理方式
    if(selectField=='processMode'){
      obj='editInfo.processMode';
    }

    if(id && name){
      this.setData({
        [id]:null,
        [name]:''
      })
    }

    if(obj){
      this.setData({
        [obj]:null
      })
    }

    this.onCloseSelect();
  },

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;    

    this.setData({
      valueSearch: e.detail
    }) 

    //业务员
    if(selectField=='salesman'){
      this.getSalesmanList();
		}
		
		//故障类型
    if(selectField=='faultType'){
      this.getFaultTypeList();
		}

		//处理方式
    if(selectField=='processMode'){
      this.getProcessModeList();
		}	
  },

  //查询故障类型
  getFaultTypeList(){
    let param = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: 'faultType',
        selectFields: ['id','name','shutdown']
      }
		}
		
		if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:{
              id: item.id,
							name: item.name,
							shutdown: item.shutdown
            }
          });
        });

        this.setData({
          selectList: arr
        })
      }else{
        this.setData({
          selectList: []
        })
      }
    }).catch((error) => {
    })
  },

  //查询处理方式
  getProcessModeList(){
    let param = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: 'processMode',
        selectFields: ['id','name']
      }
		}
		
		if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:{
              id:item.id,
              name:item.name
            }
          });
        });

        this.setData({
          selectList: arr
        })
      }else{
        this.setData({
          selectList: []
        })
      }
    }).catch((error) => {
    })
  },

  //添加服务记录
  onAddService(){
    let sList=this.data.serviceList;

    sList.push({
      content: null,
      datetime: util.timeFormat(new Date())
    });

    this.setData({ 
      serviceList: sList
    })
  },

  //获取服务记录输入
  onGetService(e){
    let idx=e.currentTarget.dataset.index;
    let val=e.detail;
    let sList=this.data.serviceList;
   
    sList.forEach((item,index) => {
      if(index==idx){
        item.content=val.trim();
      }
    }); 

    this.setData({ 
      serviceList: sList
	  })
  },

  //删除服务记录
  ondeleteService(e){    
    let idx=e.currentTarget.dataset.index;
    let sList=this.data.serviceList;
    let arr=[];
    
    sList.forEach((item,index) => {
      if(index!=idx){
        arr.push(item);
      }
    });

    this.setData({ 
      serviceList: arr 
    })
  },

  //只保存服务记录
  onSaveService(){ 
    let serviceDetails=this.data.editInfo.serviceDetails;
    let serviceList=this.data.serviceList;
    let newService=[];

    serviceList.forEach(item => {
      if(item.content){
        newService.push(item);
      }	
    });

    if(newService.length){
      serviceDetails=serviceDetails.concat(newService);

      let param={
        className:'afterSaleMaintainOrder',
        data:{
          id: this.data.paramObj.id,
          serviceDetails: serviceDetails  
        }
      } 

      CommonService.goSave(param).then(res=>{
        if (res.statusCode == 200 && res.data.success == true){
          Toast.success('成功');
          setTimeout(() => {
            //返回列表页并刷新数据
            this.backAndRefresh();
          }, 1000);
        }else{
          Toast.fail('操作失败');
        }
      }).catch((error) => {
      })

    }else{
      Toast.fail('请输入服务记录');
    } 
  },

  //修改设备表业务员
  changeEquipmentSalesman(){
    let param={
      className:'equipment',
      data:{
        id: this.data.paramObj.equipmentId,
        salesman: this.data.editInfo.salesman
      }
    }

    CommonService.goSave(param).then(res=>{
    }).catch((error) => {
    })
  },

  //查询业务员
  getSalesmanList(){
    let param = {
      isAuth: true,
      className: 'user',
      data: {
        searchAll: true,
        type: 1,
        //业务部
        depart: 5936,
        selectFields: ['id', 'userName', 'code']
      }
    }
  
    if(this.data.valueSearch){
      param.data.userName='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text: item.userName,
            id: item.id,
            obj: {
              id: item.id,
              name: item.userName,
              code: item.code
            }
          });
        });

        this.setData({
          selectList: arr
        })
      }else{
        this.setData({
          selectList: []
        })
      }
    }).catch((error) => {
    })
  },

  //获取设备信息
  getEquipmentInfo(){
    let param = {
      isAuth: true,
      className: 'equipment',
      data: {
        id: this.data.paramObj.equipmentId,
        selectFields: ['id','salesman','equipmentNo']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
				let result=res.data.data.result[0];

				//设备信息
				this.setData({
					equipmentInfo: result
				})

				//业务员
        if(result.salesman){
          this.setData({
            salesman: {
              id: result.salesman.id,
              name: result.salesman.name,
              code: result.salesman.code
            }
          })
        }
      }

      //获取维修工单修改数据
      this.getInfo();

    }).catch((error) => {
    })
	},
	
	//是否修改设备状态为故障
	shutdownDevice(id){
		let param = {
			id: id
		}
		CommonService.shutdown(param).then(res => {}).catch((error) => {})
	},

	//外援上门次数
  onChangeNum(e){
		let num = 'editInfo.numberOfForeignVisits';
    this.setData({
      [num]: e.detail
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})